import type { TagProps } from 'element-plus'
import type { RequirementStatus } from '@/api/requirements'
import { useDefectStates } from '@/composables/useDefectStates'
import { useStateStore } from '@/stores/state'
import { ModuleType } from '@/types/core'

export type TagType = NonNullable<TagProps['type']>

export const formatDate = (dateString: string) => {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  })
}

export const formatRelativeTime = (timestamp: number) => {
  const now = Date.now()
  const diff = now - timestamp
  const minutes = Math.floor(diff / 60000)
  const hours = Math.floor(diff / 3600000)
  const days = Math.floor(diff / 86400000)

  if (minutes < 1) return '刚刚'
  if (minutes < 60) return `${minutes}分钟前`
  if (hours < 24) return `${hours}小时前`
  if (days < 30) return `${days}天前`
  return formatDate(new Date(timestamp).toISOString())
}

export const getStatusType = (status: string): TagType => {
  const statusMap: Record<string, TagType> = {
    planning: 'info',
    active: 'primary',
    in_progress: 'primary',
    completed: 'success',
    on_hold: 'warning',
    cancelled: 'danger',
    archived: 'info'
  }
  return statusMap[status] || 'info'
}

export const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    planning: '规划中',
    active: '进行中',
    in_progress: '进行中',
    completed: '已完成',
    on_hold: '已暂停',
    cancelled: '已取消',
    archived: '已归档'
  }
  return statusMap[status] || status
}


export const getPriorityType = (priority: string): TagType => {
  if (!priority) return 'info'
  
  // 基础映射（作为后备方案）
  const priorityMap: Record<string, TagType> = {
    lowest: 'info',
    low: 'info',
    medium: 'warning',
    high: 'danger',
    highest: 'danger',
    urgent: 'danger',
    critical: 'danger'
  }
  
  // 如果缓存中有数据，优先使用缓存
  // 注意：这里需要异步获取，但为了保持函数签名同步，先使用基础映射
  // 实际使用时应通过 composable 或 store 预先加载优先级数据
  return priorityMap[priority.toLowerCase()] || 'info'
}

export const getPriorityText = (priority: string) => {
  if (!priority) return '未设置'
  
  // 基础映射（作为后备方案）
  const priorityMap: Record<string, string> = {
    lowest: '最低',
    low: '低',
    medium: '中',
    high: '高',
    highest: '最高',
    urgent: '紧急',
    critical: '严重'
  }
  
  // 如果缓存中有数据，优先使用缓存
  // 注意：这里需要异步获取，但为了保持函数签名同步，先使用基础映射
  // 实际使用时应通过 composable 或 store 预先加载优先级数据
  return priorityMap[priority.toLowerCase()] || priority
}

export const getCategoryText = (category: string) => {
  const categoryMap: Record<string, string> = {
    web: '网站开发',
    app: '应用开发',
    desktop: '桌面应用',
    ai: '人工智能',
    data: '数据分析',
    other: '其他',
    web_development: 'Web 开发',
    mobile_app: '移动应用',
    desktop_app: '桌面应用',
    api_development: 'API 开发',
    data_analysis: '数据分析',
    machine_learning: '机器学习',
    infrastructure: '基础设施',
    testing: '测试',
    maintenance: '维护',
    research: '研究'
  }
  return categoryMap[category] || category
}

// 任务状态类型 - 从状态管理系统动态获取
export const getTaskStatusType = (status: string): TagType => {
  const stateStore = useStateStore()
  const state = stateStore.getStateByCode(status, ModuleType.TASK)
  
  if (state) {
    // 根据状态名称或代码判断类型
    const name = state.name?.toLowerCase() || ''
    const code = state.code?.toLowerCase() || ''
    
    // 完成状态
    if (name.includes('完成') || name.includes('已完成') ||
        code.includes('completed') || code.includes('done') || code.includes('finished')) {
      return 'success'
    }
    // 进行中状态
    if (name.includes('进行中') || name.includes('进行') || name.includes('处理中') ||
        code.includes('in_progress') || code.includes('processing') || code.includes('doing')) {
      return 'primary'
    }
    // 评审/审核状态
    if (name.includes('评审') || name.includes('审核') ||
        code.includes('reviewing') || code.includes('review')) {
      return 'warning'
    }
    // 取消状态
    if (name.includes('取消') || code.includes('cancelled') || code.includes('cancel')) {
      return 'danger'
    }
    // 待处理/新建状态
    if (name.includes('待处理') || name.includes('待办') || name.includes('新建') ||
        code.includes('pending') || code.includes('todo') || code.includes('new')) {
      return 'info'
    }
  }
  
  return 'info'
}

// 任务状态文本 - 从状态管理系统动态获取
export const getTaskStatusText = (status: string) => {
  if (!status) return '未知'
  
  const stateStore = useStateStore()
  const state = stateStore.getStateByCode(status, ModuleType.TASK)
  
  if (state && state.name) {
    return state.name
  }
  
  // 如果没有找到，使用后备映射
  const statusMap: Record<string, string> = {
    new: '新建',
    pending: '待处理',
    todo: '待办',
    in_progress: '进行中',
    processing: '处理中',
    doing: '进行中',
    reviewing: '评审中',
    review: '评审',
    completed: '已完成',
    done: '已完成',
    finished: '已完成',
    cancelled: '已取消',
    cancel: '已取消',
    closed: '已关闭',
    on_hold: '已暂停',
    paused: '已暂停',
    blocked: '已阻塞',
    rejected: '已拒绝'
  }
  
  // 尝试匹配状态代码（不区分大小写）
  const lowerStatus = status.toLowerCase()
  if (statusMap[lowerStatus]) {
    return statusMap[lowerStatus]
  }
  
  // 如果还是没有找到，返回原始状态值
  return status
}

export const getTaskPriorityType = (priority: string) => getPriorityType(priority)
export const getTaskPriorityText = (priority: string) => getPriorityText(priority)

// 缺陷状态类型 - 从状态管理系统动态获取
export const getDefectStatusType = (status: string): TagType => {
  const { getStatusType } = useDefectStates()
  return getStatusType(status)
}

// 缺陷状态文本 - 从状态管理系统动态获取
export const getDefectStatusText = (status: string) => {
  if (!status) return '未知'
  
  const { getStateName } = useDefectStates()
  const stateName = getStateName(status)
  
  // 如果从状态管理系统获取到了名称且不是原始状态值，直接返回
  if (stateName && stateName !== status) {
    return stateName
  }
  
  // 如果没有找到，使用后备映射
  const statusMap: Record<string, string> = {
    new: '新建',
    open: '打开',
    assigned: '已分派',
    in_progress: '处理中',
    processing: '处理中',
    fixing: '修复中',
    resolved: '已解决',
    verified: '已验证',
    closed: '已关闭',
    cancelled: '已取消',
    cancel: '已取消',
    reopened: '已重新打开',
    rejected: '已拒绝',
    duplicate: '重复',
    wont_fix: '不修复',
    cannot_reproduce: '无法重现'
  }
  
  // 尝试匹配状态代码（不区分大小写）
  const lowerStatus = status.toLowerCase()
  if (statusMap[lowerStatus]) {
    return statusMap[lowerStatus]
  }
  
  // 如果还是没有找到，返回原始状态值
  return status
}

export const getDefectPriorityType = (priority: string) => getPriorityType(priority)
export const getDefectPriorityText = (priority: string) => getPriorityText(priority)

// 需求状态类型 - 从状态管理系统动态获取
export const getRequirementStatusType = (status: RequirementStatus): TagType => {
  if (!status) return 'info'
  
  const stateStore = useStateStore()
  const lowerStatus = status.toLowerCase()
  
  // 首先尝试精确匹配（大小写敏感）
  let state = stateStore.getStateByCode(status, ModuleType.REQUIREMENT)
  
  // 如果精确匹配失败，尝试大小写不敏感匹配
  if (!state) {
    const requirementStates = stateStore.getStatesByModule(ModuleType.REQUIREMENT)
    state = requirementStates.find(s => s.code.toLowerCase() === lowerStatus)
  }
  
  if (state) {
    // 根据状态名称或代码判断类型
    const name = state.name?.toLowerCase() || ''
    const code = state.code?.toLowerCase() || ''
    
    // 完成状态
    if (name.includes('完成') || name.includes('已完成') || name.includes('已实现') ||
        code.includes('completed') || code.includes('done') || code.includes('implemented')) {
      return 'success'
    }
    // 进行中状态
    if (name.includes('进行中') || name.includes('进行') || name.includes('测试中') ||
        code.includes('in_progress') || code.includes('testing')) {
      return 'primary'
    }
    // 评审/审核状态
    if (name.includes('评审') || name.includes('审核') || name.includes('已批准') ||
        code.includes('review') || code.includes('approved')) {
      return 'warning'
    }
    // 取消/拒绝状态
    if (name.includes('取消') || name.includes('拒绝') ||
        code.includes('cancelled') || code.includes('rejected')) {
      return 'danger'
    }
    // 草稿/新建状态
    if (name.includes('草稿') || name.includes('新建') ||
        code.includes('draft') || code.includes('new')) {
      return 'info'
    }
    // 已分配/待分析状态
    if (name.includes('分配') || name.includes('分析') ||
        code.includes('assigned') || code.includes('pending_analys') || code.includes('analysis')) {
      return 'warning'
    }
  }
  
  // 后备映射：根据状态代码判断类型
  if (lowerStatus.includes('assigned')) {
    return 'warning'
  }
  if (lowerStatus.includes('pending_analys') || lowerStatus.includes('analysis')) {
    return 'warning'
  }
  
  return 'info'
}

// 需求状态文本 - 从状态管理系统动态获取
export const getRequirementStatusText = (status: RequirementStatus) => {
  if (!status) return '未知'
  
  const stateStore = useStateStore()
  const lowerStatus = status.toLowerCase()
  
  // 首先尝试精确匹配（大小写敏感）
  let state = stateStore.getStateByCode(status, ModuleType.REQUIREMENT)
  
  // 如果精确匹配失败，尝试大小写不敏感匹配
  if (!state) {
    const requirementStates = stateStore.getStatesByModule(ModuleType.REQUIREMENT)
    state = requirementStates.find(s => s.code.toLowerCase() === lowerStatus)
  }
  
  if (state && state.name) {
    return state.name
  }
  
  // 如果没有找到，使用后备映射
  const statusMap: Record<string, string> = {
    draft: '草稿',
    new: '新建',
    open: '打开',
    pending: '待处理',
    waiting: '等待中',
    assigned: '已分配',
    pending_analys: '待分析',
    pending_analysis: '待分析',
    pending_ana: '待分析',
    analysing: '分析中',
    analysis: '分析中',
    approved: '已批准',
    approve: '已批准',
    active: '进行中',
    in_progress: '进行中',
    developing: '开发中',
    testing: '测试中',
    test: '测试',
    review: '评审',
    reviewing: '评审中',
    under_review: '评审中',
    completed: '已完成',
    done: '已完成',
    finished: '已完成',
    implemented: '已实现',
    deployed: '已部署',
    cancelled: '已取消',
    cancel: '已取消',
    rejected: '已拒绝',
    closed: '已关闭',
    suspend: '已暂停',
    suspended: '已暂停',
    on_hold: '已暂停',
    archived: '已归档',
    deleted: '已删除'
  }
  
  // 尝试匹配状态代码（不区分大小写）
  if (statusMap[lowerStatus]) {
    return statusMap[lowerStatus]
  }
  
  // 如果还是没有找到，返回原始状态值
  return status
}

export const getRequirementPriorityType = (priority: string) => getPriorityType(priority)
export const getRequirementPriorityText = (priority: string) => getPriorityText(priority)

export const getActivityIconClass = (type: string) => `activity-icon-${type || 'default'}`

